#include <cstdio>
#include <string.h>
#include <iostream>

using namespace std;

int main(){

  int cases;
  scanf("%d\n\n", &cases);
  
  int instruction;
  for(int i=0;i<cases;i++){
    int RAM[1000]={0};      
    int reg[10]={0};

    int position =0;
    char str[4];
    while(gets(str)!=NULL && strcmp(str, "") !=0){
      instruction = 100*(str[0]-'0')+10*(str[1]-'0') + str[2]-'0';
      RAM[position++]=instruction;
    }
    
    position=0;
    int actions =0;
    while(RAM[position]!=100){
      actions++;
      int tempPosition;
      int first = (RAM[position]/10) %10;
      int second = RAM[position]%10;
      
      int condition = RAM[position]/100; 
      switch (condition){
      case 2:
	reg[first] = second;
	position++;
	break;
      case 3:
	reg[first]+=second;
	reg[first]= reg[first]%1000;
	position++;
	break;
      case 4:
	reg[first]*=second;
	reg[first]= reg[first]%1000;
	position++;
	break;
      case 5:
	reg[first]=reg[second];
	position++;
	break;
      case 6:
	reg[first]+=reg[second];
	reg[first]= reg[first]%1000;
	position++;
	break;
      case 7:
	reg[first]*=reg[second];
	reg[first]= reg[first]%1000;
	position++;
	break;
      case 8:
	tempPosition = reg[second];
	reg[first] = RAM[tempPosition];
	position++;
	break;
      case 9:
	tempPosition = reg[second];
	RAM[tempPosition] = reg[first];
	position++;
	break;
      case 0:
	if(reg[second]){
	  position = reg[first];
	}else{
	  position++;	  
	}
	break;
      }
    }
    if(i){
     printf("\n");
    }
	printf("%d\n", ++actions);
  }
}
